package com.niit.utils;
import java.sql.*;

public class DBHelper {
    private static String url="jdbc:mysql://localhost:3306/washpainting?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&useSSL=false";
    private static String user="root";
    private  static String password="510422";
    private static Connection conn=null;
    //获取数据库链接/
    public static Connection getConnection(){
        Connection conn = null ;
        try {
            //1.加载驱动  导入驱动包
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/washpainting?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&useSSL=false";
            //2.获取数据库链接 。
            conn = DriverManager.getConnection(url, "root", "510422");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return conn ;
    }
    //查询通用方法/
    public static ResultSet executeQuery(String sql,Object...obj){
        Connection conn=getConnection();//同一个类可以直接使用方法名来来调用
        ResultSet rs=null;
        try {
            //将sql语句发送给数据库，让数据实行预编译处理，加快执行的速度
            PreparedStatement pre = conn.prepareStatement(sql);
            //传递参数
            for(int i=0;i<obj.length;i++){
                pre.setObject(i+1,obj[i]);//
            }
            rs = pre.executeQuery();//执行查询

        } catch (Exception e) {
            e.printStackTrace();
        }

        return rs;
    }
    //执行修改
    public static int executeUpdate(String sql ,Object...obj){
        Connection conn = getConnection();
        int count = -1 ;
        try {
            //执行预编译语句
            PreparedStatement pre = conn.prepareStatement(sql);
            //传递参数
            for (int i = 0; i < obj.length; i++) {
                pre.setObject(i+1, obj[i]);
            }
            //返回受影响的行数
            count = pre.executeUpdate();
            pre.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count ;
    }
}
